<template>
  <div class="flex direction-column width-100 height-100 padding bg-white">
    <h2 class="table-title text-center">
      {{title}}
      <el-button type="primary" style="float: right;" :loading="submitting" icon="el-icon-top" @click="saveOrUpdate">上报</el-button>
      <el-button type="primary" style="float: right;margin-right: 10px;" icon="el-icon-bottom" @click="exportData">导出</el-button>
    </h2>
    <table class="report-table" ref="table">
      <thead>
        <tr>
          <th colspan="3" width="300">月份</th>
          <th v-for="item in columns" :key="item">{{item}}</th>
          <th class="no-border-right">{{year}}年</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th rowspan="6">能源指标</th>
          <th colspan="2">
            <div class="table-cell">
              <div class="label">用电量</div>
              <p class="small">（吨标准煤）</p>
            </div>
          </th>
          <td v-for="(item, index) in electric" :key="index">
            <div class="input-cell">
              <el-popover trigger="click" :content="electric[index]" placement="top" popper-class="cell-popper">
                <input slot="reference" type="text" :value="electric[index]" @click="clickHandler" @input="inputHandler(electric, index, $event)">
              </el-popover>
            </div>
          </td>
          <td class="readonly">
            <el-tooltip :content="electricTotal" placement="top">
              <div class="span-cell">
                {{electricTotal}}
              </div>
            </el-tooltip>
          </td>
        </tr>
        <tr>
          <th colspan="2">
            <div class="table-cell">
              <div class="label">用水量</div>
              <p class="small">（吨）</p>
            </div>
          </th>
          <td v-for="(item, index) in water" :key="index">
            <div class="input-cell">
              <el-popover trigger="click" :content="water[index]" placement="top" popper-class="cell-popper">
                <input slot="reference" type="text" :value="water[index]" @click="clickHandler" @input="inputHandler(water, index, $event)">
              </el-popover>
            </div>
          </td>
          <td class="readonly">
            <el-tooltip :content="waterTotal" placement="top">
              <div class="span-cell">
                {{waterTotal}}
              </div>
            </el-tooltip>
          </td>
        </tr>
        <tr>
          <th colspan="2">
            <div class="table-cell">
              <div class="label">用气量</div>
              <p class="small">（吨标准煤）</p>
            </div>
          </th>
          <td v-for="(item, index) in gas" :key="index">
            <div class="input-cell">
              <el-popover trigger="click" :content="gas[index]" placement="top" popper-class="cell-popper">
                <input slot="reference" type="text" :value="gas[index]" @click="clickHandler" @input="inputHandler(gas, index, $event)">
              </el-popover>
            </div>
          </td>
          <td class="readonly">
            <el-tooltip :content="gasTotal" placement="top">
              <div class="span-cell">
                {{gasTotal}}
              </div>
            </el-tooltip>
          </td>
        </tr>
        <tr>
          <th colspan="2">
            <div class="table-cell">
              <div class="label">能源回收利用量</div>
              <p class="small">（吨标准煤）</p>
            </div>
          </th>
          <td v-for="(item, index) in recycle" :key="index">
            <div class="input-cell">
              <el-popover trigger="click" :content="recycle[index]" placement="top" popper-class="cell-popper">
                <input slot="reference" type="text" :value="recycle[index]" @click="clickHandler" @input="inputHandler(recycle, index, $event)">
              </el-popover>
            </div>
          </td>
          <td class="readonly">
            <el-tooltip :content="recycleTotal" placement="top">
              <div class="span-cell">
                {{recycleTotal}}
              </div>
            </el-tooltip>
          </td>
        </tr>
        <tr>
          <th colspan="2">
            <div class="table-cell">
              <div class="label">能源转化产出量</div>
              <p class="small">（吨标准煤）</p>
            </div>
          </th>
          <td v-for="(item, index) in output" :key="index">
            <div class="input-cell">
              <el-popover trigger="click" :content="output[index]" placement="top" popper-class="cell-popper">
                <input slot="reference" type="text" :value="output[index]" @click="clickHandler" @input="inputHandler(output, index, $event)">
              </el-popover>
            </div>
          </td>
          <td class="readonly">
            <el-tooltip :content="outputTotal" placement="top">
              <div class="span-cell">
                {{outputTotal}}
              </div>
            </el-tooltip>
          </td>
        </tr>
        <tr>
          <th colspan="2" class="readonly">
            <div class="table-cell">
              <div class="label">
                综合能源消费量
                <el-tooltip placement="top" content="综合能源消费量=(用电量+用气量)-(回收利用量+转化产出量)">
                  <i class="el-icon-info"></i>
                </el-tooltip>
              </div>
              <p class="small">（吨标准煤）</p>
            </div>
          </th>
          <td v-for="(item, index) in comprehensive" :key="index" class="readonly">
            <el-tooltip :content="comprehensive[index]" placement="top">
              <div class="span-cell">
                {{comprehensive[index]}}
              </div>
            </el-tooltip>
          </td>
          <td class="readonly">
            <el-tooltip :content="comprehensiveTotal" placement="top">
              <div class="span-cell">
                {{comprehensiveTotal}}
              </div>
            </el-tooltip>
          </td>
        </tr>
        <tr>
          <th rowspan="4" class="no-border-bottom">能效指标</th>
          <th colspan="2">
            <div class="table-cell">
              <div class="label">工业总产值</div>
              <p class="small">（万元）</p>
            </div>
          </th>
          <td v-for="(item, index) in gdp" :key="index">
            <div class="input-cell">
              <el-popover trigger="click" :content="gdp[index]" placement="top" popper-class="cell-popper">
                <input slot="reference" type="text" :value="gdp[index]" @click="clickHandler" @input="inputHandler(gdp, index, $event)">
              </el-popover>
            </div>
          </td>
          <td class="readonly">
            <el-tooltip :content="gdpTotal" placement="top">
              <div class="span-cell">
                {{gdpTotal}}
              </div>
            </el-tooltip>
          </td>
        </tr>
        <tr>
          <th colspan="2" class="readonly">
            <div class="table-cell">
              <div class="label">
                万元产值综合能耗
                <el-tooltip placement="top" content="万元产值综合能耗=(综合能源消费量×1000)÷工业总产值">
                  <i class="el-icon-info"></i>
                </el-tooltip>
              </div>
              <p class="small">（千克标准煤/万元）</p>
            </div>
          </th>
          <td v-for="(item, index) in gdpRatio" :key="index" class="readonly">
            <el-tooltip :content="gdpRatio[index]" placement="top">
              <div class="span-cell">
                {{gdpRatio[index]}}
              </div>
            </el-tooltip>
          </td>
          <td class="readonly">
            <el-tooltip :content="gdpRatioTotal" placement="top">
              <div class="span-cell">
                {{gdpRatioTotal}}
              </div>
            </el-tooltip>
          </td>
        </tr>
        <tr>
          <th colspan="2">
            <div class="table-cell">
              <div class="label">工业增加值</div>
              <p class="small">（万元）</p>
            </div>
          </th>
          <td v-for="(item, index) in add" :key="index">
            <div class="input-cell">
              <el-popover trigger="click" :content="add[index]" placement="top" popper-class="cell-popper">
                <input slot="reference" type="text" :value="add[index]" @click="clickHandler" @input="inputHandler(add, index, $event)">
              </el-popover>
            </div>
          </td>
          <td class="readonly">
            <el-tooltip :content="addTotal" placement="top">
              <div class="span-cell">
                {{addTotal}}
              </div>
            </el-tooltip>
          </td>
        </tr>
        <tr>
          <th colspan="2" class="readonly">
            <div class="table-cell">
              <div class="label">
                万元增加值综合能耗
                <el-tooltip placement="top" content="万元增加值综合能耗=(综合能源消费量×1000)÷工业增加值">
                  <i class="el-icon-info"></i>
                </el-tooltip>
              </div>
              <p class="small">（千克标准煤/万元）</p>
            </div>
          </th>
          <td v-for="(item, index) in addRatio" :key="index" class="readonly">
            <el-tooltip :content="addRatio[index]" placement="top">
              <div class="span-cell">
                {{addRatio[index]}}
              </div>
            </el-tooltip>
          </td>
          <td class="readonly">
            <el-tooltip :content="addRatioTotal" placement="top">
              <div class="span-cell">
                {{addRatioTotal}}
              </div>
            </el-tooltip>
          </td>
        </tr>
      </tbody>
    </table>
    <div style="height: 160px;"></div>
  </div>
</template>

<script>
import { stringToPositiveNumber } from '@/utils'
import { loadEnterpriseReporting, saveOrUpdate } from '@/api/enterpriseReporting'
import { simpleTable2Sheet } from '@/utils/sheet'

export default {
  name: 'fill-in-enterprise-indicators',
  data () {
    return {
      submitting: false,

      year: new Date().getFullYear(),
      columns: Array(12).fill(undefined).map((v, i) => (i + 1) + '月'),
      water: Array(12).fill('-'),
      electric: Array(12).fill('-'),
      gas: Array(12).fill('-'),
      recycle: Array(12).fill('-'),
      output: Array(12).fill('-'),
      gdp: Array(12).fill('-'),
      add: Array(12).fill('-'),

      inputIndex: -1,
    }
  },
  computed: {
    title () {
      return `${this.year}年企业能源指标填报表`
    },
    comprehensive () {
      const { electric, gas, recycle, output } = this
      return Array(electric.length).fill(1).map((v, i) => {
        const result = (((Number(electric[i]) || 0) + (Number(gas[i]) || 0)) - ((Number(recycle[i]) || 0) + (Number(output[i]) || 0)))
        return result ? result.toFixed(2) : '-'
      })
    },
    gdpRatio () {
      const { comprehensive, gdp } = this
      return Array(comprehensive.length).fill(1).map((v, i) => {
        return Number(gdp[i]) ? ((Number(comprehensive[i]) || 0) * 1000 / Number(gdp[i])).toFixed(2) : '-'
      })
    },
    addRatio () {
      const { comprehensive, add } = this
      return Array(comprehensive.length).fill(1).map((v, i) => {
        return Number(add[i]) ? ((Number(comprehensive[i]) || 0) * 1000 / Number(add[i])).toFixed(2) : '-'
      })
    },
    electricTotal () {
      return this.electric.reduce((acc, v) => {
        acc = (Number(acc) || 0) + (Number(v) || 0)
        return acc
      }).toFixed(2)
    },
    waterTotal () {
      return this.water.reduce((acc, v) => {
        acc = (Number(acc) || 0) + (Number(v) || 0)
        return acc
      }).toFixed(2)
    },
    gasTotal () {
      return this.gas.reduce((acc, v) => {
        acc = (Number(acc) || 0) + (Number(v) || 0)
        return acc
      }).toFixed(2)
    },
    recycleTotal () {
      return this.recycle.reduce((acc, v) => {
        acc = (Number(acc) || 0) + (Number(v) || 0)
        return acc
      }).toFixed(2)
    },
    outputTotal () {
      return this.output.reduce((acc, v) => {
        acc = (Number(acc) || 0) + (Number(v) || 0)
        return acc
      }).toFixed(2)
    },
    comprehensiveTotal () {
      // const { electricTotal, gasTotal, recycleTotal, outputTotal } = this
      // return ((Number(electricTotal) || 0) + (Number(gasTotal) || 0) - (Number(recycleTotal) || 0) - (Number(outputTotal) || 0)).toFixed(2)
      return this.comprehensive.reduce((acc, v) => {
        acc = (Number(acc) || 0) + (Number(v) || 0)
        return acc
      }).toFixed(2)
    },
    gdpTotal () {
      return this.gdp.reduce((acc, v) => {
        acc = (Number(acc) || 0) + (Number(v) || 0)
        return acc
      }).toFixed(2)
    },
    gdpRatioTotal () {
      const { gdpTotal, comprehensiveTotal } = this
      return Number(gdpTotal) ? ((Number(comprehensiveTotal) || 0) * 1000 / Number(gdpTotal)).toFixed(2) : '-'
    },
    addTotal () {
      return this.add.reduce((acc, v) => {
        acc = (Number(acc) || 0) + (Number(v) || 0)
        return acc
      }).toFixed(2)
    },
    addRatioTotal () {
      const { addTotal, comprehensiveTotal } = this
      return Number(addTotal) ? ((Number(comprehensiveTotal) || 0) * 1000 / Number(addTotal)).toFixed(2) : '-'
    },
  },
  beforeDestroy () {
    this.unbindArrowKeyEvent()
  },
  mounted () {
    this.loadEnterpriseReporting()
    this.initInputIndex()
    this.bindArrowKeyEvent()
  },
  methods: {
    initInputIndex () {
      const inputs = document.querySelectorAll('.input-cell input')
      inputs.forEach((input, index) => {
        input.dataset.inputIndex = index
      })
    },
    eventHandler (e) {
      const { key, keyCode } = e
      if (keyCode < 37 || keyCode > 40 || key.indexOf('Arrow') === -1) {
        return false
      }
      const inputs = document.querySelectorAll('.input-cell input')
      let inputIndex = this.inputIndex
      const length = this.columns.length
      // ArrowUp
      if (key === 'ArrowUp' || keyCode === 38) {
        inputIndex -= length
      }
      // ArrowDown
      if (key === 'ArrowDown' || keyCode === 40) {
        inputIndex += length
      }
      // ArrowLeft
      if (key === 'ArrowLeft' || keyCode === 37) {
        inputIndex--
      }
      // ArrowRight
      if (key === 'ArrowRight' || keyCode === 39) {
        inputIndex++
      }
      if (inputIndex >= 0 && inputIndex <= inputs.length - 1) {
        this.inputIndex = inputIndex
      }
      inputs[this.inputIndex]?.click()
    },
    bindArrowKeyEvent () {
      document.addEventListener('keyup', this.eventHandler, false)
    },
    unbindArrowKeyEvent () {
      document.removeEventListener('keyup', this.eventHandler, false)
    },
    inputHandler (type, index, evt) {
      const value = stringToPositiveNumber(evt.target.value)
      evt.target.value = value
      type.splice(index, 1, value)
    },
    clickHandler (evt) {
      evt.target.select()
      this.inputIndex = Number(evt.target.dataset.inputIndex)
    },
    loadEnterpriseReporting () {
      return loadEnterpriseReporting().then(res => {
        if (res.code === 200) {
          res.data = res.data || []
          if (res.data.length === 0) {
            return
          }
          if (res.data.length === 13) {
            res.data = res.data.slice(0, 12)
          }
          function handler (key) {
            return function iterator (v) {
              return v[key] || '-'
            }
          }
          this.water = res.data.map(handler('waterConsumption'))
          this.electric = res.data.map(handler('energyUsed'))
          this.gas = res.data.map(handler('gasConsumption'))
          this.recycle = res.data.map(handler('amountRecycled'))
          this.output = res.data.map(handler('conversionOutput'))
          this.gdp = res.data.map(handler('industrialOutput'))
          this.add = res.data.map(handler('industrialAddedValue'))
        }
      })
    },
    saveOrUpdate () {
      const { water, electric, gas, recycle, output, comprehensive, gdp, gdpRatio, add, addRatio } = this
      const params = Array(water.length).fill(1).map((v, i) => ({
        month: i + 1,
        waterConsumption: water[i],
        energyUsed: electric[i],
        gasConsumption: gas[i],
        amountRecycled: recycle[i],
        conversionOutput: output[i],
        comprehensiveEnergyConsumption: comprehensive[i],
        industrialOutput: gdp[i],
        tenThousandOutputValue: gdpRatio[i],
        industrialAddedValue: add[i],
        tenThousandValueAdded: addRatio[i],
      }))
      this.submitting = true
      return saveOrUpdate(params).then(res => {
        if (res.code === 200) {
          this.$message.success('提交成功')
        }
      }).finally(() => {
        this.submitting = false
      })
    },
    exportData () {
      const table = this.$refs.table
      const fileName = this.title + '.xlsx'
      simpleTable2Sheet(table, fileName, this.title)
    },
  },
}
</script>

<style scoped>
.table-title {
  margin-top: 60px;
  margin-bottom: 20px;
}
.report-table {
  width: 100%;
  height: 100%;
  border-spacing: 0;
  border: 1px solid #dbdbdb;
  text-align: center;
  table-layout: fixed;
}
.report-table td,
.report-table th {
  border-bottom: 1px solid #dbdbdb;
  border-right: 1px solid #dbdbdb;
  padding: 0;
}
.report-table thead th {
  padding: 1rem;
}
@media screen and (max-width: 1400px) {
  .report-table thead th {
    padding: 1rem .5rem;
  }
}
tbody tr th:last-child,
tbody tr td:last-child {
  border-right: 0;
}
tbody tr:last-child th,
tbody tr:last-child td {
  border-bottom: 0;
}
.no-border-bottom {
  border-bottom: 0 !important;
}
.no-border-right {
  border-right: 0 !important;
}
.table-cell .small {
  margin-bottom: 0;
  margin-top: 5px;
  font-weight: normal;
  font-size: 12px;
}
.input-cell input,
.input-cell {
  width: 100%;
  height: 100%;
}
.input-cell input {
  border-color: transparent;
  outline: none;
  background: transparent;
  -webkit-appearance: none;
  display: block;
  text-align: center;
  font-size: 12px;
  padding-left: 5px;
  padding-right: 5px;
  transition: all .6s;
}
.input-cell input:focus {
  border-color: black;
}
.readonly {
  background: #f6f6f6;
  overflow: hidden;
  font-size: 12px;
}
</style>
